<?php

namespace app\admin\controller\classes;

use addons\exam\enum\PaperMode;
use app\admin\model\exam\QuestionModel;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 题库管理
 *
 * @icon fa fa-circle-o
 */
class Tiku extends Backend
{
    protected $noNeedRight = ['*'];
    /**
     * Tiku模型对象
     * @var \app\admin\model\classes\Tiku
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\classes\Tiku;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * Selectpage搜索
     *
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }

    public function index()
    {

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $params = $this->request->get();
            if(empty($params['limit']))
            {
                $limit = 1000;
            }
            else
            {
                $limit = $params['limit'];
            }

            $order = $params['order'];
            $sort = $params['sort'];


            $db2 = Db::connect('db2');
            $where = ['status'=>1];

            /*if(!empty($params['search']))
            {
                $where['nickname'] = ['like','%'.$params['search'].'%'];
            }*/
            $list = $db2->table('fa_classes_tiku')->where($where)->order($sort, $order)->paginate($limit);

            /*list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['province','city','district','tiku'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);*/
            $rows = $list->items();

            $result = array("total" => $list->total(), "rows" => $rows);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                //$this->model>valid($params);
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);

                    // 保存试卷固定题目
                    //$this->saveFixQuestion($row, $params, 'edit');
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if (!empty($row['questions'])){
            $questions=json_decode($row['questions'],true);
            $question_id_arr=array_column($questions,'id');

            $row['questions'] = QuestionModel::getFixListByTkIN($question_id_arr, ['cates']);
        }
        $this->view->assign("row", $row);
        //$this->view->assign("configs", json_decode($row['configs'], true));
        return $this->view->fetch();
    }

    public function question()
    {

        if ($this->request->isAjax()) {

            $tiku_id = $this->request->get("tiku_id");

            $db2 = Db::connect('db2');
            $tiku = $db2->table('fa_classes_tiku')->find($tiku_id);

            $questions = json_decode($tiku['questions'],true);
            $ids = '';
            foreach ($questions as $v)
            {
                $ids .= $v['id'] . ',';
            }
            $ids = trim($ids,',');
            $where['a.id'] = ['in',$ids];
            $questions_list = $db2->table('fa_exam_question a')
                ->join('fa_exam_cate b','a.cate_id=b.id')
                ->where($where)
                ->field('a.*,b.name as cate_name')
                ->select();
            $total = $db2->table('fa_exam_question a')->where($where)->count();

//            dump($questions_list);die;
            $result = array("total" => $total, "rows" => $questions_list);

            return json($result);
        }
        $tiku_id = $this->request->get("id");
        $this->view->assign('tiku_id',$tiku_id);
        return $this->view->fetch();
    }

    public function view($ids = null)
    {

        $db2 = Db::connect('db2');
        $row = $db2->table('fa_exam_question')->find($ids);

        $this->view->assign("row", $row);
        $options_json = json_decode($row['options_json'],true);
        // dump($options_json);exit;
        $this->view->assign("options_json", $options_json);
        $QuestionModel = new QuestionModel;
        $kindList = $QuestionModel->getKindList();
//        dump($kindList);die;
        $this->view->assign("kindList", $kindList);
        return $this->view->fetch();
    }

    public function allocation()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            //$this->model>valid($params);
            $params = $this->preExcludeFields($params);
            if (empty($params['tiku_id']) || empty($params['name']))
            {
                $this->error('参数错误！');
            }
            if(empty($params['parent_id_tt']))
            {
                $this->error('请选择分类');
            }

            Db::startTrans();
            try {
                $tiku_id = $params['tiku_id'];
                $db2 = Db::connect('db2');
                $tiku = $db2->table('fa_classes_tiku')->find($tiku_id);

                $questions = json_decode($tiku['questions'],true);
                $ids = '';
                foreach ($questions as $v)
                {
                    $ids .= $v['id'] . ',';
                }
                $ids = trim($ids,',');
                $where['id'] = ['in',$ids];
                $questions_list = $db2->table('fa_exam_question')->where($where)->select();

                $cate_where = [
                    'name' => $params['name'],
                    'parent_id' => $params['parent_id_tt'],
                    'deletetime' => null
                ];
                $cate_list = Db::name('exam_cate')->where($cate_where)->find();
                if(empty($cate_list))
                {
                    $cate_data = [
                        'kind' => 'QUESTION',
                        'level' => 4,
                        'name' => $params['name'],
                        'parent_id' => $params['parent_id_tt'],
                        'uid' => $this->auth->id,
                    ];
                    $cate_id = Db::name('exam_cate')->insertGetId($cate_data);
                }
                else
                {
                    $cate_id = $cate_list['id'];
                }

                foreach ($questions_list as $k => $v)
                {
                    $data = [
                        'cate_id' => $cate_id,
                        'kind' => $v['kind'],
                        'title' => $v['title'],
                        'explain' => $v['explain'],
                        'difficulty' => $v['difficulty'],
                        'options_json' => $v['options_json'],
                        'options_img' => $v['options_img'],
                        'options_extend' => $v['options_extend'],
                        'answer' => $v['answer'],
                        'status' => $v['status'],
                        'other_url' => $v['other_url'],
                        'describe' => $v['describe'],
                        'other_name' => $v['other_name'],
                        'createtime' => time(),
                        'uid' => $this->auth->id,
                    ];

                    Db::name('exam_question')->insert($data);
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $tiku_id = $this->request->get("id");
        $this->view->assign('tiku_id',$tiku_id);
        $parentlist = Db::name('exam_cate')->where(['parent_id'=>0,'kind'=>'QUESTION','uid'=>$this->auth->id,'deletetime'=>null])->select();
        $this->view->assign("parentList", $parentlist);

        return $this->view->fetch();
    }

    public function son_cate()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if($params['qid'] == 0){
                return json(['code'=>1,'msg'=>'','list'=>[]]);
            }
            $list = Db::name('exam_cate')->where(['parent_id'=>$params['qid'],'deletetime'=>null])->select();
            if(!empty($list))
            {
                return json(['code'=>100,'msg'=>'','list'=>$list]);
            }
            return json(['code'=>1,'msg'=>'','list'=>[]]);
        }
    }
}
